<?php
class CategoryControl extends Control{
	
	public function __construct(){
		parent::__construct();

		//子菜单
		$submenu = array(
			array(
				'alias' => 'categoryList',
				'title' => '分类列表',
				'url'	=> C('site_admin') . 'index.php?a=menu&m=categoryList',
			),
			array(
				'alias' => 'addCategory',
				'title' => '添加分类',
				'url'	=> C('site_admin') . 'index.php?a=menu&m=addCategory',
			),
			array(
				'alias' => 'editCategory',
				'title' => '编辑分类',
				'url'	=> C('site_admin') . 'index.php?a=menu&m=editCategory',
			),
		);
		
		$this->assign('mainMenu','category');
		$this->assign('submenu',$submenu);
	}
	
	public function index(){
		$this->categoryList();
	}
	
	/**
	 * 新加分类
	 */
	public function addCategory($type='add'){
		if($_POST['dosubmit'] == 1){
			//新加 or 编辑
			$data['id'] = (int)$_POST['category_id'];
			$data['name'] = trim($_POST['category_name']);
			$data['description'] = trim($_POST['category_desc']);
			
			if($data['name'] == ''){
				$url = C('site_url').'index.php?c=category&m=addCategory';
				$msg = '分类名称不能为空...';
				redirect($url,3,$msg);
			}
			
			if(empty($data['id'])){
				$result = M('Category')->addCategory($data);
			}else{
				$result = M('Category')->editCategory($data);
			}
			
			$url = C('site_url').'index.php?c=category&m=categoryList';
			$msg = '操作'.($result ? '成功' : '失败').'...';
			$msg = iconv('utf-8','gbk',$msg);
			redirect($url,3,$msg);
		}else{
			//展示表单
			$category_id = (int)$_GET['category_id'];
			if($category_id){
				$category = M('Category')->getCategoryById($category_id);
			}
			
			if($type == 'edit'){
				$this->assign('subMenu','editCategory');
			}else{
				$this->assign('subMenu','addCategory');
			}
			$this->assign('type',$type);
			$this->assign('category',$category);
			$this->assign('category_id',$category_id);
			$this->assign('formToken',token());
			$this->display('add_category');
		}
	}
	
	/**
	 * 删除分类
	 * @return json
	 */
	public function delCategory(){
		$id = (int)$_POST['id'];
		$result = M('Category')->delCategory($id);
		$info = '删除'.($result ?  '成功' : '失败');
		$status = (int)$result;
		ajaxReturn('',$info,$status);
	}
	
	/**
	 * 编辑分类
	 */
	public function editCategory(){
		$this->addCategory('edit');
	}
	
	/**
	 * 分类列表
	 */
	public function categoryList(){
		$categories = M('Category')->getCategories();
		$this->assign('subMenu','categoryList');
		$this->assign('categories',$categories);
		$this->display('category_list');
	}
}
?>